package application.handlers;

import application.RequestHandler;
import application.UserLoggedManager;
import contracts.requests.LoginByTokenRequest;
import contracts.responses.LoginByTokenResponse;
import domain.entities.User;
import domain.services.UserDomainService;
import internal.InternalResult;
import io.netty.channel.Channel;
import util.ChannelHelper;

/**
 * @author wyl
 */
public class LoginByTokenHandler extends RequestHandler<LoginByTokenRequest, LoginByTokenResponse> {
    @Override
    public LoginByTokenResponse handle(LoginByTokenRequest loginByTokenRequest, Channel requestChannel) {
        InternalResult result = UserDomainService.Instance.tryLogin(loginByTokenRequest.token);
        String newToken = "";
        boolean success = false;
        String errorMessage = "";
        String connId = ChannelHelper.getConnId(requestChannel);
        User u = (User) result.getData();
        if (result.isSuccess()) {
            result = UserDomainService.Instance.buildUserToken(u);
            if (result.isSuccess()) {
                newToken = result.getData().toString();
                success = true;
                UserLoggedManager.login(connId, u);
            }
        } else {
            errorMessage = result.getErrorMessage();
        }

        return new LoginByTokenResponse(success,
                connId,
                errorMessage,
                newToken);
    }
}
